from py2neo import Graph, Node, Relationship, NodeMatcher

graph = Graph("bolt://localhost:7687", auth=("neo4j", "12345678"))


def transfer_money(sender_name, receive_name, amount):
    # 开启事件
    tx = graph.begin()
    try:
        sender = graph.nodes.match("Account", name=sender_name).first()
        if not sender:
            raise ValueError(f"发送方的账户{sender_name}不存在")
        receiver = graph.nodes.match("Account", name=receive_name).first()
        if not receiver:
            raise ValueError(f"接收方的账户{receive_name}不存在")
        if sender["balance"] < amount:
            raise ValueError(f"账户{sender_name}余额不足")
        sender["balance"] -= amount
        tx.push(sender)  # update 更新
        receiver["balance"] += amount
        tx.push(receiver)

        transfer = Relationship(sender, "TRANSFER", receiver, amount=amount)
        tx.create(transfer)  # create创建新节点
        graph.commit(tx)
    except Exception as e:
        graph.rollback(tx)
        print(f"转账失败:{str(e)}")


if __name__ == "__main__":
    graph.run(
        """
            MERGE (a:Account {name:'张三',balance:1000})
            MERGE (b:Account {name:'李四',balance:1000})
        """
    )
    transfer_money("张三", "李四", 500)
    # transfer_money("张三", "李四", 600)
    transfer_money("张三", "王五", 100)
